//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/subject/paper_detail_model.dart';
import 'package:hktk_app/model/subject/records_model.dart';
// import 'package:hktk_app/pages/question/chapter_question_page.dart';
import 'package:hktk_app/pages/subject/child/paper_detail_widget.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/back_button_widget.dart';


/// 88
/// 试卷详情页面
class PaperDetailPage extends StatefulWidget {
  /// 试卷id
  final String id;

  /// 栏目id
  final String columnId;

  /// 考试是否继续
  final String? recordId;

  /// 考试对应的下标
  final int index;
  final int categoryId;

  const PaperDetailPage({
    super.key,
    required this.id,
    required this.columnId,
    this.recordId,
    required this.index,
    required this.categoryId
  });

  @override
  State<PaperDetailPage> createState() => _PaperDetailPageState();
}

class _PaperDetailPageState extends State<PaperDetailPage> {
  late BuildContext _context;

  /// 试卷相关信息
  late PaperDetailModel _paper;

  /// 试卷初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 记录id，只记录试卷考试的
  late String? _recordId;

  /// 试卷交卷监听通知
  late StreamSubscription<EventPaperSubmit> _eventSubmit;

  @override
  void initState() {
    super.initState();
    debugPrint("paperDetailPage 页面 -> initState 方法执行 ===> ${widget.columnId}");
    debugPrint("");
    _recordId = widget.recordId;
    _futureInit = _initData();

    // 监听试卷是否交卷
    _eventSubmit = eventBus.on<EventPaperSubmit>().listen((event) {
      debugPrint("paperDetailPage 页面 -> 监听是否交卷触发 ===> ");
      _recordId = null;
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("paperDetailPage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    eventBus.fire(EventPaperDetailClose(
      index: widget.index,
      recordId: _recordId,
      columnId: widget.columnId,
    ));
    _eventSubmit.cancel();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("paperDetailPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    // 获取安全边距
    var top = MediaQuery.of(context).padding.top;
    var bottom = MediaQuery.of(context).padding.bottom;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Container(
        margin: EdgeInsets.only(top: top, bottom: bottom),
        child: Column(
          children: [
            _showTitle(),
            Expanded(child: _futureData()),
          ],
        ),
      ),
    );
  }

  /// 标题显示组件
  _showTitle() {
    return Container(
      height: 88,
      margin: EdgeInsets.symmetric(horizontal: 48),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 占位使用
          SizedBox(
            width: 48,
            height: 48,
          ),
          Text(
            "试卷详情",
            style: FontUtil.fontBlack1(34, fontWeight: FontWeight.w500),
          ),
          BackButtonWidget.close(pageContext: _context),
        ],
      ),
    );
  }

  /// 加载中组件
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;

          if (!map["suc"]) {
            if (map["msg"] != null) {
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                ToastUtil.show(context: _context, msg: map["msg"]);
                Navigator.pop(_context);
              });
            }
          }
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      _paper = await SubjectDao.paperDetail(id: widget.id);

      map["suc"] = true;
    } catch (e) {
      debugPrint("paperDetailPage 页面 -> 加载数据发生异常 ===> $e");
      _paper = PaperDetailModel();
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("paperDetailPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 显示对应内容方法
  Widget _content() {
    return Column(
      children: [
        Expanded(child: _showPaper()),
        _showButtons(),
      ],
    );
  }

  /// 显示按钮组
  _showButtons() {
    return Container(

      padding: EdgeInsets.symmetric(horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buttonItem(true),
          _buttonItem(false),
        ],
      ),
    );
  }

  /// 按钮显示
  _buttonItem(bool practice) {
    return GestureDetector(
      onTap: () {
        _onTapFun(practice);
      },
      child: Container(
        padding: EdgeInsets.only(top: 5,bottom: 8,left: 25,right: 25),
        decoration: BoxDecoration(
            color: practice ? colorWhite1 : colorBlue1,
            borderRadius: BorderRadius.all(Radius.circular(44)),
            border: Border.all(color: colorBlue1, width: 1)),
        child: Center(
          child: Text(
            practice ? "练习模式" : "考试模式",
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w500,
              color: practice ? colorBlue1 : colorWhite1,
            ),
          ),
        ),
      ),
    );
  }

  /// 显示试卷页面
  _showPaper() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 23),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [
            hiSpace(height: 20),
            _showPaperItem(),
            hiSpace(height: 40),
          ],
        ),
      ),
    );
  }

  /// 显示试卷内容
  _showPaperItem() {
    return Stack(

      children: [
        _background(),
        Positioned(
          top: 100,
          left: 20,
          right: 20,
          bottom: 40,
          child: _itemContent(),
        ),
      ],
    );
  }

  /// 显示试卷背景
  _background() {
    return SizedBox(
      height: 1.sh-88-60,
      child: SvgPicture.asset(
        "images/subject/file_pocket.svg",
        fit: BoxFit.cover,
      ),
    );
  }

  /// 显示试卷内容
  _itemContent() {
    return Container(
      width: 325,

      padding: EdgeInsets.symmetric(vertical: 40, horizontal: 30),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        gradient: const LinearGradient(
            colors: [colorWhite1, colorWhite3],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight),
      ),
      child: _showListView(),
    );
  }

  /// 信息显示
  _showListView() {
    return PaperDetailWidget.paper(
      name: _paper.name,
      typeName: _paper.paperType?.desc,
      totalScore: _paper.totalScore,
      scoreRight: _paper.examTime,
      qCount: _paper.qcount,
      qCountRight: _paper.stuCount,
      content: _paper.content,
    );
  }

  /// 试卷对应模式点击方法
  void _onTapFun(bool practice) async {
    if (practice) {
      // 练习模式，直接加载试卷记录
      _loadRecord(practice);
    } else {
      // 考试模式，判断是否需要弹框提醒是否需要继续答题
      debugPrint("paperDetailPage 页面 -> _recordId ===> $_recordId");
      if (_recordId != null) {
        // 已有记录，提示是否需要继续考试
        bool? value = await ToastUtil.showDialogBox(
          context: _context,
          contentText: "是否继续未完成的考试?",
          btnLeftText: "重新考试",
          btnRightText: "继续考试",
        );
        debugPrint("paperDetailPage 页面 -> 是否继续未完成的考试对话框返回值value ===> $value");
        if (value != null) {
          if (value) {
            // 继续考试
            _pushPage(practice: practice, recordsId: _recordId!);
          } else {
            // 重新考试
            _loadRecord(practice, strict: true);
          }
        }
      } else {
        // 没有记录，直接进入考试页面
        _loadRecord(practice);
      }
    }
  }

  /// 加载记录方法
  _loadRecord(bool practice, {bool strict = false}) {
    DataModel dataModel = dataUtilComm.dataModel;
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 加载记录
    SubjectDao.generatePaperRecords(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      paperId: _paper.id!,
      columnId: widget.columnId,
      result: false,
      strict: strict,
      practiceModel: practice,
    ).then((RecordsModel model) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      if (!practice) {
        _recordId = model.id!;
      }
      _pushPage(practice: practice, recordsId: model.id!);
    }).catchError((e) {
      debugPrint("paperDetailPage 页面 -> 试卷库创建试卷记录发生异常 ===> $e");
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        debugPrint("paperDetailPage 页面 -> dao异常 ===> ${e.msg}");
        msg = e.msg;
      }
      // 提示
      ToastUtil.show(context: _context, msg: msg);
    });
  }

  // practice : 是否是练习模式
  // recordsId : 试卷记录id
  /// 跳转对应页面
  void _pushPage({
    required bool practice,
    required String recordsId,
  }) {
     // 跳转做题页面
    Navigator.pushNamed(context, "/chapter-question",arguments: {
      "id": recordsId,
      "collType": CollectionTypeEnum.paper,
      "columnId": widget.columnId,
      "cId": _paper.id!,
      "rType": practice
          ? CtEnum.paperRecordChapterPractice
          : CtEnum.paperRecordPaperLibrary,
      "practice": practice,
      "examTime": _paper.examTime ?? 0,
    });

  }
}
